﻿using System.Collections;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Net;

namespace UdpServer
{
    public class NetUdpClient
    {
        public static NetUdpClient Instance;
        UdpClient udp;
        Thread th;
        static NetUdpClient()
        {
            Instance = new NetUdpClient();
        }

        public void Close()
        {
            th.Abort();
            udp.Close();
        }

        public void Init(int port)
        {
            udp = new UdpClient(port);
            th = new Thread(ReceiveMsg);
            th.IsBackground = true;
            th.Start();
            System.Console.WriteLine("UDPServer启动成功");
        }

        public void Send(string address, TransMsg o)
        {
            var s = address.Split(':');
            //var bs = BinarySerializer.Serialize(o);
            byte[] bs = ProtobufHelper.Serialize(o);
            udp.Send(bs, bs.Length, s[0], int.Parse(s[1]));
        }

        void ReceiveMsg()
        {
            var p = new IPEndPoint(IPAddress.Any, 0);
            while (true)
            {
                byte[] bs = udp.Receive(ref p);
                TransMsg o = ProtobufHelper.DeSerialize<TransMsg>(bs);
                //var o = BinarySerializer.Deserialize<TransMsg>(bs);
                MessageCenter.Instance.AddMsg(o);
            }
        }
    }
}